﻿using Microsoft.Extensions.DependencyInjection;
using RxxAdmin.Common;
using RxxAdmin.Common.Helper;
using SqlSugar;

namespace RxxAdmin.Extensions;

public static class SqlsugarSetup
{
    public static void AddSqlsugarSetup(this IServiceCollection services)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        // 默认添加主数据库连接
        if (!AppSettings.MainDB.IsNullOrEmpty())
        {
            MainDb.CurrentDbConnId = AppSettings.MainDB;
        }
        BaseDBConfig.MutiConnectionString.allDbs.ForEach(m =>
        {
            var config = new ConnectionConfig()
            {
                ConfigId = m.ConnId.ObjToString().ToLower(),
                ConnectionString = m.Connection,
                DbType = (DbType)m.DbType,
                IsAutoCloseConnection = true,
                // Check out more information: https://github.com/anjoy8/Blog.Core/issues/122
                //IsShardSameThread = false,
                MoreSettings = new ConnMoreSettings()
                {
                    //IsWithNoLockQuery = true,
                    IsAutoRemoveDataCache = true,
                    SqlServerCodeFirstNvarchar = true,
                },
                InitKeyType = InitKeyType.Attribute
            };
            if (SqlSugarConst.LogConfigId.ToLower().Equals(m.ConnId.ToLower()))
            {
                BaseDBConfig.LogConfig = config;
            }
            else
            {
                if (string.Equals(config.ConfigId.ObjToString(), MainDb.CurrentDbConnId,
                            StringComparison.CurrentCultureIgnoreCase))
                {
                    BaseDBConfig.MainConfig = config;
                }
                else if (m.ConnId.ToLower().StartsWith(MainDb.CurrentDbConnId.ToLower()))
                {
                    //复用连接
                    BaseDBConfig.ReuseConfigs.Add(config);
                }
                BaseDBConfig.ValidConfig.Add(config);
            }

            BaseDBConfig.AllConfigs.Add(config);
        });

        if (BaseDBConfig.LogConfig is null)
        {
            throw new ApplicationException("未配置Log库连接");
        }

        // SqlSugarScope是线程安全，可使用单例注入
        // 参考：https://www.donet5.com/Home/Doc?typeId=1181
        services.AddSingleton<ISqlSugarClient>(o =>
        {
            return new SqlSugarScope(BaseDBConfig.AllConfigs);
        });
    }
}
